import re
import requests
from lxml import etree
import json
from datetime import datetime


def get_html():
    """获取网页内容"""
    url = "https://music.163.com/discover/toplist"
    headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }
    response = requests.get(url, headers=headers)
    
    # 生成带时间戳的文件名
    current_time = datetime.now()
    filename = f"toplist_{str(current_time.year)[2:]}_{current_time.month}_{current_time.day}.html"
    
    # 将HTML内容保存到文件
    with open(filename, "w", encoding="utf-8") as f:
        f.write(response.text)
    
    return filename  # 返回文件名供后续使用


def extract_song_info(html_content):
    """从HTML内容中提取歌曲信息"""
    selector = etree.HTML(html_content)
    
    song_list = selector.xpath('//div[@id="song-list-pre-cache"]//ul[@class="f-hide"]/li/a')
    
    songs = []
    for a_tag in song_list:
        song_info = {
            "title": a_tag.text.strip(),
            "href": a_tag.get("href"),
            "id": None
        }
        
        # 从链接中提取歌曲ID
        if song_info["href"]:
            match = re.search(r'id=(\d+)', song_info["href"])
            if match:
                song_info["id"] = match.group(1)
        
        songs.append(song_info)
    return songs


def load_html_from_file(file_path):
    """从文件加载HTML内容"""
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            return f.read()
    except FileNotFoundError:
        print(f"文件未找到: {file_path}")
        return ""
    except Exception as e:
        print(f"读取文件失败: {file_path} | {str(e)}")
        return ""


if __name__ == "__main__":
    # 获取HTML并保存，同时获取生成的文件名
    html_file_path = get_html()
    
    # 读取HTML文件
    html_content = load_html_from_file(html_file_path)
    
    # 提取歌曲信息
    if html_content:
        songs = extract_song_info(html_content)
        
        # 以JSON格式保存结果
        with open("songs_info.json", "w", encoding="utf-8") as f:
            json.dump(songs, f, ensure_ascii=False, indent=4)
        print("歌曲信息已保存到songs_info.json")
        
        
        # 打印歌曲信息
        # for song in songs:
        #     print(f"歌曲ID: {song['id']}, 标题: {song['title']}, 链接: {song['href']}")
    else:
        print("未获取到有效的HTML内容")
